package de.mssp.sensorkit.compass;

import de.mssp.sensorkit.R;
import android.app.Activity;
import android.graphics.Matrix;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;

public class CompassActivity extends Activity implements SensorEventListener 
{
	private SensorManager sensorManager;
	private ImageView imageView;
	Matrix rotationMatrix = new Matrix();

	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.compass);
		
		//Create CompassImage
		imageView = (ImageView) findViewById(R.id.imageFile);
		
		//Get general SeonsorManager
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
	}

	/** Register for the updates when Activity is in foreground */
	@Override
	protected void onResume() 
	{
		super.onResume();
		
		//Register for listening to sensor events
		sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	/** Stop the updates when Activity is paused */
	@Override
	protected void onPause() 
	{
		super.onPause();
		
		//Stop listening
		sensorManager.unregisterListener(this);
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) 
	{
		//Ignore
	}

	public void onSensorChanged(SensorEvent event) 
	{
		//Center Image
		int x = imageView.getDrawable().getMinimumWidth() /2;
		int y = imageView.getDrawable().getMinimumWidth() /2;

		//Rotate Compass Image
		rotationMatrix.setRotate((event.values[0]) * -1, x, y);
		imageView.setImageMatrix(rotationMatrix);

	}

}
